import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_todo_2019/common/application.dart';
import 'package:flutter_todo_2019/common/common.dart';
import 'package:flutter_todo_2019/event/tab_change_event.dart';
import 'package:flutter_todo_2019/event/mine_msg_count_event_new.dart';
import 'package:flutter_todo_2019/event/refresh_todo_event.dart';
import 'package:flutter_todo_2019/event/refresh_todo_list_event.dart';
import 'package:flutter_todo_2019/page/api/apis_service.dart';
import 'package:flutter_todo_2019/page/base/base_widget.dart';
import 'package:flutter_todo_2019/page/flags/todo_add_screen.dart';
import 'package:flutter_todo_2019/page/flags/todo_list_screen.dart';
import 'package:flutter_todo_2019/page/mode/base_model.dart';
import 'package:flutter_todo_2019/page/mode/todo_list_model.dart';
import 'package:flutter_todo_2019/page/utils/GlobalInfo.dart';
import 'package:flutter_todo_2019/page/utils/item_utils.dart';
import 'package:flutter_todo_2019/page/utils/route_util.dart';
import 'package:flutter_todo_2019/page/utils/sp_util.dart';
import 'package:flutter_todo_2019/page/utils/theme_util.dart';
import 'package:flutter_todo_2019/page/utils/toast_util.dart';
import 'package:flutter_todo_2019/test/nd/TestChildPage.dart';
import 'package:flutter_todo_2019/widgets/item_todo_list.dart';
import 'package:flutter_todo_2019/widgets/loading_dialog.dart';
import 'package:flutter_todo_2019/widgets/refresh_helper.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// TODO 待办列表页面
/// TODO 状态栏 https://blog.csdn.net/qq_32687703/article/details/93889702
/// Flutter ScrollView嵌套ListView滑动冲突
///
class TodoListScreenPpreant extends BaseWidget {
  @override
  BaseWidgetState<BaseWidget> attachState() {
    return new TodoListScreenPpreantState();
  }
}

class TodoListScreenPpreantState extends BaseWidgetState<TodoListScreenPpreant>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  ScrollController _scrollViewController;

  int _selectedIndex = 0;
  int todoType = 0;
  Map<String, List<TodoBean>> map = Map();

  final SlidableController slidableController = SlidableController();

  int _page = 1;
  List<TodoBean> _todoBeanList = new List();

  var tabs = <Tab>[
    new Tab(
        child: Text("持续",
            style: new TextStyle(
                fontSize: 15.0,
                fontWeight: FontWeight.bold,
             ))),
    new Tab(child: Text("学习",
        style: new TextStyle(
          fontSize: 15.0,
          fontWeight: FontWeight.bold,
        ))),
    new Tab(child: Text("工作",
        style: new TextStyle(
          fontSize: 15.0,
          fontWeight: FontWeight.bold,
        ))),
    new Tab(child: Text("生活",
        style: new TextStyle(
          fontSize: 15.0,
          fontWeight: FontWeight.bold,
        ))),
  ];

  @override
  void initState() {
    height = 20;
    setAppBarVisible(true);
    _scrollViewController = ScrollController(initialScrollOffset: 0.0);
    _tabController = new TabController(vsync: this, length: 4);
    super.initState();
    showLoading();
    getNoTodoList();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    showContent();
  }

//  @override
////  AppBar attachAppBar() {
////    return new AppBar(
////        bottom: new TabBar(
////      labelColor: Colors.blue[300],
////      unselectedLabelColor: Colors.white,
////      indicatorColor: Colors.white,
////      indicatorPadding: EdgeInsets.only(left: 35, right: 35),
////      tabs: tabs,
////      controller: _tabController,
////    ));
////  }
//
  @override
  AppBar attachAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0, // 隐藏阴影
    );
  }

//  @override
//  AppBar attachAppBar() {
//    return null;
//  }

//  @override
//  Widget attachContentWidget(BuildContext context) {
//    return Scaffold(
//
//        body:
//        TabBarView(
//            controller: this._tabController,
//            children: pages,
//            physics: NeverScrollableScrollPhysics()));
//  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return Scaffold(
        body: NestedScrollView(
            controller: _scrollViewController,
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverAppBar(
                    elevation: 0, // 隐藏阴影

                    pinned: true,
                    backgroundColor: Colors.white,
                    floating: true,
                    expandedHeight: 240,
                    flexibleSpace: FlexibleSpaceBar(
                      collapseMode: CollapseMode.pin,
                      background: Container(
                        //头部整个背景颜色
                        height: double.infinity,
                        color: Colors.white,
                        child: Column(children: <Widget>[
                          ItemUtils.swiperPage(context, null)
                        ]
//                            _buildTabBarBg()],
                            ),
                      ),
                    ),
                    bottom: new TabBar(
                      labelColor: ThemeUtils.currentThemeColor,
                      unselectedLabelColor: Colors.grey,
                      indicatorColor: ThemeUtils.currentThemeColor,
                      indicatorPadding: EdgeInsets.only(left: 35, right: 35),
                      tabs: tabs,
                      controller: _tabController,
                    ))
              ];
            },
            body: TabBarView(
              controller: this._tabController,
              children: [
                _buildListView(""),
                _buildListView(""),
                _buildListView(""),
                _buildListView(""),
              ],
            )));
  }

  @override
  void onClickErrorWidget() {}

  Widget _buildBanner() {
    return Container(
      margin: EdgeInsets.only(left: 16.0, right: 16.0, top: 12.0),
      height: 144,
      child: Swiper(
          //第三方的banner库：flutter_swiper
          itemBuilder: (BuildContext context, int index) {
            return Container(
              width: double.infinity,
              height: 144,
              child: Image.network(
                "https://github.com/best-flutter/flutter_swiper/raw/master/banner.jpg",
                height: double.infinity,
                fit: BoxFit.fill,
              ),
            );
          },
          itemCount: 3,
          scale: 0.9,
          pagination: new SwiperPagination()),
    );
  }

  Widget _buildTabBarBg() {
    return Container(
      //TabBar圆角背景颜色
      height: 50,
      child: ClipRRect(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(15), topRight: Radius.circular(15)),
          child: Container(color: Colors.white)),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _scrollViewController.dispose();
    _tabController.dispose();
  }

  Widget _buildListView(String s) {
    return ListView.builder(
      padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
      itemBuilder: itemView,
      physics: AlwaysScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: _todoBeanList.length,
    );
  }

  Widget itemView(BuildContext context, int index) {
    TodoBean item = _todoBeanList[index];
    bool isShowSuspension = false;
    if (map.containsKey(item.dateStr)) {
      if (map[item.dateStr].length > 0) {
        if (map[item.dateStr][0].id == item.id) {
          isShowSuspension = true;
        }
      }
    }
    return ItemTodoList(
      isTodo: true,
      item: item,
      slidableController: slidableController,
      isShowSuspension: isShowSuspension,
      todoType: todoType,
    );
  }

  /// 获取待办TODO列表数据
  Future getNoTodoList() async {
    _page = 1;
    apiService.getNoTodoList((TodoListModel model) {
      if (model.errorCode == Constants.STATUS_SUCCESS) {
        if (model.data.datas.length > 0) {
          setState(() {
            _todoBeanList.clear();
            _todoBeanList.addAll(model.data.datas);
          });

          rebuildData();
        }
      } else {
        T.show(msg: model.errorMsg);
      }
    }, (error) {}, todoType, _page);
  }

  /// 重新构建数据
  void rebuildData() {
    map.clear();
    Set<String> set = new Set();
    _todoBeanList.forEach((bean) {
      set.add(bean.dateStr);
    });

    set.forEach((s) {
      List<TodoBean> list = new List();
      map.putIfAbsent(s, () => list);
    });

    _todoBeanList.forEach((bean) {
      map[bean.dateStr].add(bean);
    });
    if (null != _todoBeanList && _todoBeanList.length > 0)
      //TODO 数据组装完毕
      SPUtil.putString(
          GlobalInfo.MSG_NOFINSH_COUNT, _todoBeanList.length.toString());
    Application.eventBus.fire(new CountMsgNewEvent());
  }
}
